<?php

namespace App\Console\Commands;

use App\Util\RabbitMqTest;
use Illuminate\Console\Command;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:rabbit_work';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'rabbit work model';
    protected  $queueName = 'test_queue1';
    protected  $queueName2 = 'test_queue2';
    protected  $exchangeName = 'test_exchange1';
    protected  $routingKey = 'exchange1_queue2';
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->topicConsumer();
    }

    /**
     * work模式的consumer
     */
    public function workConsumer()
    {
        $conn = RabbitMqTest::getInstance()->GetClient();
        $channel = $conn->channel();
        $channel->basic_qos(null,1,null);
        $callBack = function ($msg){
            echo $msg->body;
            $msg->ack();
        };
        $channel->basic_consume($this->queueName,'',false,false,false,false,$callBack);
        while($channel->is_open()) {
            $channel->wait();
        }
        $channel->close();
        $conn->close();
    }

    /**
     * topic 模式下的消费者
     */
    public function topicConsumer()
    {
        $conn = RabbitMqTest::getInstance()->GetClient();
        $channel =  $conn->channel();
        $channel->exchange_declare($this->exchangeName,'topic',false,true);
        $channel->queue_declare($this->queueName2,false,true,false,false);
        $channel->queue_bind($this->queueName2,$this->exchangeName,$this->routingKey);
        $channel->basic_qos(null,1,null);
        $callBack = function (AMQPMessage $msg){
            echo $msg->body."\r\n";
            $msg->ack();
        };
        $channel->basic_consume($this->queueName2,'',false,false,false,false,$callBack);
        while($channel->is_open()) {
            $channel->wait();
        }
        $channel->close();
        $conn->close();

    }
}
